const Router = require('koa-router')
const mysql = require('../util/mysql/mysql')
const { dateFtt } = require('../util/common')
const { SUCCESS, PARAM_NOT_COMPLETE, FAIL } = require('../util/respone/index')

let news = new Router()

function checkForm(params,checkType = '*') {
  // 拼接 查询数据库语句 
  let { id, title = '', pTags = '', startDate = '', endDate = '' } = params;
  let checkNews = '', checkComments = '';
  if (id) {
    checkNews = `SELECT ${checkType} FROM news WHERE id = ${id}`
    checkComments = `SELECT comments.id,username,emails,message,c_type FROM news INNER join comments on comments.c_id = news.id where news.id = ${id}`
    return { checkNews, checkComments }
  } else if (title || pTags || (startDate && endDate)) {
    return { checkNews: `SELECT ${checkType} FROM news WHERE title LIKE '%${title}%' and pTags LIKE '%${pTags}%' and date between '${startDate}' and '${endDate}'` }
  } else {
    return { checkNews: `SELECT ${checkType} FROM news` }
  }
}

// 获取 新闻 信息
news.get('/news', async (ctx, next) => {
  // 用户post过来的数据
  let { id, pageSize = 10, pageNum = 1, record = false} = ctx.query;

  // 拼接 查询数据库 语句
  let checkSql = checkForm(ctx.query).checkNews + ` limit ${(pageNum - 1) * pageSize}, ${pageSize}`

  // 拼接 查询总数 语句
  let checkTotalSql = checkForm(ctx.query, 'COUNT(*)').checkNews
  
  let outObj = { pageSize, pageNum }; // 向外输出数据的obj
  let isSuccess = true; // 数据库中 查询操作成功标签
  // -------数据库操作------
  // 查询数据库中数据
  await mysql.check(checkSql)
    .then(async res => {
      outObj.dataList = res
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx)
    })
    
  //查询总数
  await mysql.check(checkTotalSql)
    .then(async res => {
      outObj.total = res[0]['COUNT(*)']
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx)
    })
    
  // 如果 接收到id 则查询新闻的评论
  if (id) {
    let checkSqlComment = checkForm(ctx.query).checkComments
    await mysql.check(checkSqlComment)
    .then(async res => {
      outObj.dataList[0]['comments'] = res
    })
    .catch(async err => {
      isSuccess = false
      return await FAIL(ctx)
    })
  }

  if (record) {
      // 如果前端传入record=true，则记录浏览的次数
    let newCount = outObj.dataList[0].viewCount + 1
    let updateSql = 'UPDATE news SET viewCount = ? WHERE id = ?'
    let updateSqlParams = [newCount,id]
    await mysql.update(updateSql, updateSqlParams)
      .catch(async err => {
        console.log(err)
    })
  }

  if (isSuccess) {
    await SUCCESS(ctx,outObj,"获取新闻成功！")
  }
})



// 添加新闻
news.post('/news', async (ctx, next) => {
  // 用户post过来的数据
  let { title,introduction,content,pTags,sImg } = ctx.request.body;

  // 添加 新闻的日期
  let date = dateFtt("yyyy-MM-dd hh:mm:ss",new Date())
  // -------数据库操作------
  let addSql = 'INSERT INTO news(title,introduction,content,pTags,sImg,date,viewCount) VALUES(?,?,?,?,?,?,?)'
  let addSqlParams = [title,introduction,content,pTags,sImg,date,0]
  await mysql.add(addSql, addSqlParams)
    .then(async res => {
      await SUCCESS(ctx,{},"添加新闻成功！")
    })
    .catch(async err => {
      return await FAIL(ctx, '添加新闻出错!')
  })
})

// 删除新闻
news.delete('/news', async (ctx, next) => {
  let { id } = ctx.request.body

  if (!id) { // 如果没有传入id 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }
  
  // -----数据库操作-------
  let delSql = `DELETE FROM news WHERE id = "${id}"`
  await mysql.delete(delSql)
    .then(async res => {
      await SUCCESS(ctx,{},"删除新闻成功！")
    })
    .catch(async err => {
    console.log(err)
  })
})

// 修改 新闻 信息
news.put('/news', async (ctx, next) => {
  let putParams = ctx.request.body;

  if (!putParams.id) { // 如果没有传入id 则弹出 错误：请求参数缺失
    return await PARAM_NOT_COMPLETE(ctx)
  }

  // 拼接 修改产品信息的 key值
  let keysArr = Object.keys(putParams)
  let template = keysArr.join(' = ?, ') + ' = ? '

  // -----数据库操作-------
  let updateSql = 'UPDATE news SET ' + template + 'WHERE id = ?'
  let updateSqlParams = Object.values(putParams)
  updateSqlParams.push(putParams.id)

  await mysql.update(updateSql, updateSqlParams)
    .then(async res => {
      await SUCCESS(ctx,{},"修改新闻信息成功!")
    })
    .catch(async err => {
      return await FAIL(ctx, '修改新闻信息出错!')
  })
})

module.exports = { news }